﻿using System;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class PipeAlignment : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new NotImplementedException();
				}
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				Selection selection = activeUIDocument.Selection;
				RevitVersionFuncs.ClearSelection(selection);
				for (;;)
				{
					transaction = new Transaction(document, "水管对齐");
					transaction.Start();
					ISelectionFilter selectionFilter = new PipeFilter();
					Reference reference = selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, selectionFilter, "选择基准水管");
					Pipe pipe = document.GetElement(reference) as Pipe;
					reference = selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, selectionFilter, "选择对齐水管");
					Pipe pipe2 = document.GetElement(reference) as Pipe;
					if (!YJKRevitTools.PipeAlignment(pipe, pipe2, 0.0))
					{
						MessageBox.Show("操作失败", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
					}
					transaction.Commit();
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null && 1 == (int)transaction.GetStatus())
				{
					transaction.RollBack();
				}
			}
			return result;
		}
	}
}
